import { Route, Router, Switch, Redirect } from 'react-router-dom'
import { history } from './history'
import config from './config'
import { useAppSelector } from '@src/redux/hook'
import { CSSTransition } from 'react-transition-group'
// import './index.less'

function RequireAuth({ children, auth, verificate }) {
  const token = useAppSelector(state => state.basic.token)
  const unVerificate = useAppSelector(state => state.basic.userInfo && state.basic.userInfo.is_auth === 0)
  if (!token && auth) {
    // 重定向至login页面，但是保存用户试图访问的location，这样我们可以把登陆后的用户重定向至那个页面
    return <Redirect to="/login" push />;
  }
  if (unVerificate && verificate) {
    return <Redirect to="/verification" push />;
  }
  return children;
}

/**
 * 路由配置
 */
function Main () {
  return (
    <div id='router'>
      <Router history={history}>
        {
          config.map((c) => {
            const Tag = c.component
            return (
              <Route key={c.path} path={c.path} exact={c.exact}>
                {({ match }) => {
                  return (
                    <CSSTransition
                      in={match != null}
                      timeout={500}
                      classNames={match != null ? c.push : c.pop}
                      unmountOnExit
                      key={c.path}
                    >
                      <div className='router-wrapper'>
                        <RequireAuth auth={c.auth} verificate={c.verificate}><Tag /></RequireAuth>
                      </div>
                    </CSSTransition>
                  )
                }}
              </Route>
            )
          })
        }
        <Switch>
          {
            config.map(c => <Route path={c.path} key={c.path} />)
          }
          {/* <Route path='/' exact component={() => <Redirect to='/home' />} /> */}
          <Route path='/*' exact component={() => <Redirect to='/' />} />
        </Switch>
      </Router>
    </div>
  )
}

export default Main
